package com.tanfuqi.sicent.protocol.util

import org.slf4j.LoggerFactory

import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec
import javax.crypto.spec.IvParameterSpec

object DESUtil {
    private val logger = LoggerFactory.getLogger(DESUtil::class.java)

    fun encrypt(content: ByteArray, keyBytes: ByteArray): ByteArray {
        val keySpec = DESKeySpec(keyBytes)
        val keyFactory = SecretKeyFactory.getInstance("DES")
        val key = keyFactory.generateSecret(keySpec)

        val cipher = Cipher.getInstance("DES/CBC/PKCS5Padding")
        cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(keySpec.key))
        return cipher.doFinal(content)


    }

    fun decrypt(content: ByteArray, keyBytes: ByteArray): ByteArray {
        val keySpec = DESKeySpec(keyBytes)
        val keyFactory = SecretKeyFactory.getInstance("DES")
        val key = keyFactory.generateSecret(keySpec)

        val cipher = Cipher.getInstance("DES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(keyBytes))
        return cipher.doFinal(content)
    }

}